package com.example.smartcity.app

import android.app.Application
import android.content.SharedPreferences
import android.os.Handler
import android.widget.ImageView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.request.RequestOptions
import com.example.smartcity.R
import com.example.smartcity.http.HttpCallback
import com.google.gson.Gson
import okhttp3.OkHttpClient
import okhttp3.Request
import java.lang.reflect.Type

class App : Application() {

    override fun onCreate() {
        super.onCreate()
        mainHandler = Handler(mainLooper)
        appConfig = getSharedPreferences("AppConfig", MODE_PRIVATE)
    }

    companion object {
        lateinit var mainHandler: Handler
        lateinit var appConfig: SharedPreferences

        const val HTTP_BASE_URL: String = "http://smart.ifast3.vipnps.vip"
        val client: OkHttpClient = OkHttpClient().newBuilder().build()
        private val gson = Gson()

        //封装通用网络请求方法
        fun <T> fetchData(url: String, type: Type, method: (data: T) -> Unit) {
            val request = Request.Builder()
                .url(App.HTTP_BASE_URL + url)
                .method("GET", null)
                .addHeader("Authorization", App.appConfig.getString("token", ""))
                .build()
            client.newCall(request).enqueue(object : HttpCallback() {
                override fun onSucceeded(s: String) {
                    val data = json2Object<T>(s, type)
                    data?.let {
                        mainHandler.post { method(it) }
                    }
                }
            })
        }

        //通用反序列化方法
        fun <T> json2Object(s: String, t: Type): T? {
            return gson.fromJson(s, t)
        }

        //通用图片加载方法-url
        fun fetchRCImage(
            url: String?,
            imageView: ImageView,
            radius: Int = 1,
            error: Int = R.mipmap.ic_more_service
        ) {
            Glide.with(imageView)
                .load(App.HTTP_BASE_URL + url)
                .error(error)
                .apply(RequestOptions().transform(CenterCrop(), RoundedCorners(radius)))
                .into(imageView)
        }

        //通用图片加载方法-resId
        fun fetchRCImage(
            resId: Int?, imageView: ImageView, radius: Int = 1,
            error: Int = R.mipmap.ic_more_service
        ) {
            Glide.with(imageView)
                .load(resId)
                .error(error)
                .apply(RequestOptions().transform(CenterCrop(), RoundedCorners(radius)))
                .into(imageView)
        }

    }

}